package br.com.tarlis.core.server;

import java.util.Map;

import br.com.tarlis.core.client.ActionService;
import br.com.tarlis.core.client.exception.SerializableException;
import br.com.tarlis.core.client.exception.UnexpectedException;
import br.com.tarlis.core.server.exception.CoreException;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class ActionServiceImpl extends RemoteServiceServlet implements ActionService {

	@SuppressWarnings("unchecked")
	@Override
	public <K> Map<String, K> doAction(
			String action,
			Map<String, K> parameters) 
		throws SerializableException {

		try {		
			ServerAction ca = (ServerAction) 
					Class.forName(action).newInstance();
			
			ca.setRequest(getThreadLocalRequest());
			ca.setResponse(getThreadLocalResponse());
			
			ca.setParameters((Map<String, Object>) parameters);
			return (Map<String, K>) ca.doAction();
		} catch (InstantiationException e) {
			e.printStackTrace();
			throw new UnexpectedException(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new UnexpectedException(e.getMessage(), e);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new UnexpectedException(e.getMessage(), e);
		} catch (CoreException e) {
			throw e.toSerializableException();
		}
		
	}
	
}
